package znet

import (
	"errors"
	"fmt"
	"sync"
	"tcpChat/ziface"
)

type ConnManager struct {
	Connections map[uint32]ziface.IConnection //管理的连接信息
	ConnLock    sync.RWMutex                  //读写锁
}

//创建一个链接管理部
func NewConnManager() *ConnManager {
	return &ConnManager{
		Connections: make(map[uint32]ziface.IConnection),
	}
}

//添加连接数据
func (cm *ConnManager) Add(connection ziface.IConnection) {
	//map上面加上写锁，保证数据安全
	cm.ConnLock.Lock()
	defer cm.ConnLock.Unlock()

	cm.Connections[connection.GetConnId()] = connection
}

func (cm *ConnManager) Remove(connection ziface.IConnection) {
	//map上面加上写锁，保证数据安全
	cm.ConnLock.Lock()
	defer cm.ConnLock.Unlock()

	delete(cm.Connections, connection.GetConnId())
}

func (cm *ConnManager) Get(connId uint32) (ziface.IConnection, error) {
	//加上读锁
	cm.ConnLock.RLock()
	cm.ConnLock.RLock()

	connection, ok := cm.Connections[connId]
	if ok == false {
		return nil, errors.New(fmt.Sprintf("Connection Manager MAP IS NOT %d", connId))
	}

	return connection, nil
}

func (cm *ConnManager) Len() int {
	return len(cm.Connections)
}

func (cm *ConnManager) ClearConn() {
	//map上面加上写锁，保证数据安全
	cm.ConnLock.Lock()
	defer cm.ConnLock.Unlock()

	for connId, conn := range cm.Connections {
		conn.Stop()

		delete(cm.Connections, connId)
	}
}
